import Http from '@/utils/Http';
import { Uri } from '@/constant/Constants';
import { ConfigureResponse } from '@/protocol/response/CommonResponse';
import Util from '@/utils/Util';
import { CacheKeys } from '@/constant/CacheKeys';
import UniUtil from '@/utils/UniUtil';
import LoggerUtil from '@/utils/LoggerUtil';

export namespace CommonService {
    export async function getCongirue() {
        let res = await Http.request(Uri.common_configure_query, null, new ConfigureResponse(), false);
        downloadPoster(res.inviteImgList);
        return res;
    }

    export async function getCongirueWithCache() {
        let res = await Http.request(Uri.common_configure_query, null, new ConfigureResponse(), false);
        await downloadPoster(res.inviteImgList);
        return res;
    }

    export async function downloadPoster(posterList: Array<string>) {
        if (Util.isEmpty(posterList)) {
            return;
        }
        let cachePosterList = <Array<string>>UniUtil.getStorage(CacheKeys.POSTER, Array);

        if (!Util.isEmpty(cachePosterList) && cachePosterList.length == posterList.length) {
            return cachePosterList;
        }

        cachePosterList = new Array<string>();
        for (let i = 0; i < posterList.length; i++) {
            let path = posterList[i];
            let str = await UniUtil.getImageInfo(path);
            if (!Util.isEmpty(str)) {
                cachePosterList.push(str);
            }
        }
        if (!Util.isEmpty(cachePosterList)) {
            UniUtil.setStorage(CacheKeys.POSTER, cachePosterList);
        }
        return cachePosterList;
    }

    export function getCachePosterList() {
        return <Array<string>>UniUtil.getStorage(CacheKeys.POSTER, Array);
    }

    export async function getMaxCommission() {
        let res = await getCongirue();
        if (null == res) {
            return null;
        }
        return res.shareRatioList[res.shareRatioList.length - 1];
    }
}
